package handler

import (
	"net/http"
	"strconv"

	"recruit_student_backend/internal/model"
	"recruit_student_backend/internal/repository"

	"github.com/gin-gonic/gin"
)

// CreateStudent 创建学生
func CreateStudent(c *gin.Context) {
	var student model.Student
	if err := c.ShouldBindJSON(&student); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据"})
		return
	}

	if err := repository.CreateStudent(&student); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建学生失败"})
		return
	}

	c.JSON(http.StatusCreated, student)
}

// GetStudent 获取单个学生信息
func GetStudent(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"})
		return
	}

	student, err := repository.GetStudentByID(uint(id))
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "学生不存在"})
		return
	}

	c.JSON(http.StatusOK, student)
}

// GetAllStudents 获取所有学生列表
func GetAllStudents(c *gin.Context) {
	students, err := repository.GetAllStudents()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取学生列表失败"})
		return
	}

	c.JSON(http.StatusOK, students)
}

// GetStudentsByPage 获取分页的学生列表
func GetStudentsByPage(c *gin.Context) {
	page, err := strconv.Atoi(c.DefaultQuery("page", "1"))
	if err!= nil || page < 1 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的页码"})
		return
	}

	pageSize, err := strconv.Atoi(c.DefaultQuery("page_size", "10"))
	if err!= nil || pageSize <= 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的每页数量"})
		return
	}

	students, err := repository.GetStudentsByPage(page, pageSize)
	if err!= nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取学生列表失败"})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"students": students,
	})
}

// UpdateStudent 更新学生信息
func UpdateStudent(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"})
		return
	}

	var student model.Student
	if err := c.ShouldBindJSON(&student); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求数据"})
		return
	}

	student.ID = uint(id)
	if err := repository.UpdateStudent(&student); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "更新学生失败"})
		return
	}

	c.JSON(http.StatusOK, student)
}

// DeleteStudent 删除学生
func DeleteStudent(c *gin.Context) {
	id, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的ID"})
		return
	}

	if err := repository.DeleteStudent(uint(id)); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "删除学生失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "删除成功"})
}
